package tuan.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegUtil {
	static Map<String, Pattern> patternMap = new HashMap<String, Pattern>();
	/**
	 * 获取预编译的正则表达式pattern对象
	 * @param regStr 正则表达式
	 * @return
	 */
	public static Pattern getPattern(String regStr) {		
		if (!patternMap.containsKey(regStr)) {
			Pattern pattern = Pattern.compile(regStr);
			patternMap.put(regStr, pattern);
		}
		return patternMap.get(regStr);
	}
	/**
	 * 将字符串转化为整数
	 * @param text
	 * @return
	 */
	public static int toInteger(String text) {
		return (int)toNum(text);
	}
	/**
	 * 将字符串转化为数字
	 * @param text
	 * @return
	 */
	public static double toNum(String text) {
		String num = getGroup1("(-?[0-9]+(.[0-9]+)?)",text);
		if (num != null) {
			return Double.parseDouble(num);
		}
		return 0.0;
	}
	/**
	 * 获取匹配字符串的group1子串
	 * @param regStr
	 * @param text
	 * @return
	 */
	public static String getGroup1(String regStr,String text) {
		Pattern pattern = getPattern(regStr);
		Matcher m = pattern.matcher(text);
		if (m.find()) {
			return m.group(1);
		}
		return null;
	}
	public static boolean match(String regStr,String text ) {
		Pattern pattern = getPattern(regStr);
		Matcher m = pattern.matcher(text);
		if (m.find()) {
			return true;
		}
		return false;
	}
	public static String deleteGroup1(String regStr,String text ) {
		Pattern pattern = getPattern(regStr);
		Matcher m = pattern.matcher(text);
		if (m.find()) {
			text = text.substring(0,m.start(1)) + text.substring(m.end(1));
			return text;
		}
		return text;
	}
}
